import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:fsharing/core/models/address.dart' as address;
import 'package:fsharing/core/models/cart_list.dart';
import 'package:fsharing/core/models/order_confirm.dart';
import 'package:fsharing/core/models/product_detail.dart';
import 'package:fsharing/core/viewmodels/pages/mine/order/order_checkout_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/order/order_confirm_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/pages/mine/order/order_page.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

/// 订单确认页面
class OrderConfirmPage extends StatelessWidget {
  final Map<String, int> cartIdQuantity;

  OrderConfirmPage({
    Key key,
    @required this.cartIdQuantity,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => OrderConfirmModel(
            Provider.of(context, listen: false),
            cartIdQuantity,
          ),
        ),
        ChangeNotifierProvider(
          create: (context) => OrderCheckoutModel(Provider.of(context, listen: false)),
        )
      ],
      child: BackgroundContainer(
        child: Consumer<OrderConfirmModel>(
          builder: (context, model, child) {
            switch (model.viewState) {
              case ViewState.busy:
                return Scaffold(
                  appBar: child,
                  body: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              case ViewState.error:
                return Scaffold(
                  appBar: child,
                  body: Center(
                    child: Text(model.errorMessage),
                  ),
                );
              case ViewState.success:
                return Scaffold(
                  appBar: child,
                  body: _BodyWidget(
                    orderConfirm: model.orderConfirm,
                  ),
                  bottomNavigationBar: _BottomWidget(
                    orderConfirm: model.orderConfirm,
                  ),
                );
              default:
                return Container();
            }
          },
          child: AppBar(
            leading: RoundBackButton(),
            title: Text('确认订单'),
          ),
        ),
      ),
    );
  }
}

class _BodyWidget extends StatelessWidget {
  final OrderConfirm orderConfirm;

  const _BodyWidget({
    Key key,
    @required this.orderConfirm,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: <Widget>[
        SliverPadding(
          padding: EdgeInsets.only(left: 12, right: 12, bottom: 12),
          sliver: SliverToBoxAdapter(
            child: _AddressWidget(),
          ),
        ),
        SliverPadding(
          padding: EdgeInsets.only(left: 12, right: 12, bottom: 12),
          sliver: SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                var store = orderConfirm.carts[index];
                return Column(
                  children: <Widget>[
                    _StoreHeaderWidget(store: store),
                    Theme(
                      data: lightTheme(),
                      child: Material(
                        borderRadius: BorderRadius.vertical(
                          bottom: Radius.circular(8),
                        ),
                        child: Column(
                          children: <Widget>[
                            ListView.builder(
                              physics: NeverScrollableScrollPhysics(),
                              shrinkWrap: true,
                              itemBuilder: (context, index) {
                                return _ProductItemWidget(cart: store.cartList[index]);
                              },
                              itemCount: store.cartList.length,
                            ),
                            _StoreFooterWidget(store: store),
                          ],
                        ),
                      ),
                    ),
                    Divider(
                      height: 12,
                      color: Colors.transparent,
                    ),
                  ],
                );
              },
              childCount: orderConfirm.carts.length,
            ),
          ),
        ),
      ],
    );
  }
}

class _AddressWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    OrderConfirmModel orderConfirmModel = Provider.of(context, listen: false);
    return Consumer<OrderCheckoutModel>(
      builder: (context, model, child) {
        Address address = model.address ?? orderConfirmModel.orderConfirm.defaultAddress;
        return Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/order/img_address.png'),
              fit: BoxFit.fill,
            ),
          ),
          height: 100,
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              borderRadius: BorderRadius.circular(8),
              child: Row(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.symmetric(horizontal: 17),
                    child: Image.asset('assets/images/order/ic_location.png', width: 16),
                  ),
                  Expanded(
                    child: address == null
                        ? Container(
                            child: Text('点击选择地址'),
                          )
                        : Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text.rich(
                                TextSpan(
                                  text: address.linkMan + '   ',
                                  style: TextStyle(fontSize: 17),
                                  children: [
                                    TextSpan(
                                      text: address.contactPhone,
                                      style: TextStyle(color: Color(0xFFA8A8A8), fontSize: 14),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(height: 5),
                              Text(
                                address.fullAddress,
                                style: TextStyle(color: Color(0xFFA8A8A8)),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                              SizedBox(height: 6),
                              Text(
                                '注：请填写有效地址,保持电话畅通，避免货物派送不到',
                                style: TextStyle(color: Color(0xFFF06F90), fontSize: 10),
                              )
                            ],
                          ),
                  ),
                  Icon(Icons.keyboard_arrow_right, color: Color(0xFFA8A8A8))
                ],
              ),
              onTap: () => _onAddressClicked(context),
            ),
          ),
        );
      },
    );
  }

  void _onAddressClicked(BuildContext context) async {
    OrderCheckoutModel model = Provider.of(context, listen: false);
    var result = await Navigator.of(context).pushNamed('/address', arguments: true);
    if (result is address.Address) {
      model.address = result.toAddress();
    }
  }
}

class _StoreHeaderWidget extends StatelessWidget {
  final Store store;

  const _StoreHeaderWidget({
    Key key,
    @required this.store,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/cart/img_store.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Row(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(left: 23, right: 5),
            height: 45,
            child: Image.asset('assets/images/cart/ic_store.png', width: 17),
          ),
          Text(
            store.storeName,
            style: TextStyle(fontSize: 17),
          ),
        ],
      ),
    );
  }
}

class _ProductItemWidget extends StatelessWidget {
  final Cart cart;

  const _ProductItemWidget({
    Key key,
    @required this.cart,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 单价
    String rmb;
    String jfb;
    for (Price price in cart.priceVos) {
      switch (price.coinType) {
        case 'RMB':
          rmb = price.pointCoinString;
          break;
        case 'JFB':
          jfb = price.pointCoinString;
          break;
      }
    }
    return Container(
      padding: EdgeInsets.only(left: 24, top: 8, right: 18, bottom: 8),
      height: 84,
      child: Row(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(4)),
            child: CachedNetworkImage(
              imageUrl: cart.productImage,
              width: 68,
              height: 68,
              fit: BoxFit.cover,
            ),
          ),
          SizedBox(width: 13),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  cart.productName,
                  style: TextStyle(fontSize: 16),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/cart/img_product_params.png'),
                      fit: BoxFit.fill,
                    ),
                  ),
                  width: 76,
                  height: 21,
                  child: Text(
                    '产品属性',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(width: 13),
          Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Text.rich(
                TextSpan(
                  text: '￥',
                  style: TextStyle(color: Theme.of(context).accentColor, fontSize: 13),
                  children: [
                    TextSpan(
                      text: rmb,
                      style: TextStyle(fontSize: 17),
                    ),
                    if (jfb != null)
                      TextSpan(
                        text: '分',
                        style: TextStyle(fontSize: 12),
                      ),
                    if (jfb != null)
                      TextSpan(
                        text: jfb,
                        style: TextStyle(fontSize: 17),
                      ),
                  ],
                ),
              ),
              Text(
                'x ${cart.quantity}',
                style: TextStyle(color: Colors.grey, fontSize: 16),
              ),
              Container(),
            ],
          )
        ],
      ),
    );
  }
}

class _StoreFooterWidget extends StatelessWidget {
  final Store store;

  const _StoreFooterWidget({
    Key key,
    @required this.store,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 店铺小计
    int subtotalQuantity = 0;
    double subtotalRmb = 0;
    double subtotalJfb = 0;
    for (Cart cart in store.cartList) {
      subtotalQuantity += cart.quantity;
      for (Price price in cart.priceVos) {
        switch (price.coinType) {
          case 'RMB':
            subtotalRmb += price.pointCoin * cart.quantity;
            break;
          case 'JFB':
            subtotalJfb += price.pointCoin * cart.quantity;
            break;
        }
      }
    }
    return Container(
      padding: EdgeInsets.only(left: 24, top: 18, right: 18, bottom: 18),
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Text('配送方式'),
              SizedBox(width: 12),
              Expanded(
                child: Text(
                  '普通配送',
                  style: TextStyle(color: Colors.grey),
                ),
              ),
              Text(
                '运费 ${store.freight == 0 ? '免邮' : '￥${store.freight}'} >',
              ),
            ],
          ),
          SizedBox(height: 25),
          Row(
            children: <Widget>[
              Text('发货时间'),
              SizedBox(width: 12),
              Text(
                '卖家承诺24小时内发货',
                style: TextStyle(color: Colors.grey),
              ),
            ],
          ),
          SizedBox(height: 12),
          Row(
            children: <Widget>[
              Text('订单备注'),
              SizedBox(width: 12),
              Expanded(
                child: TextField(
                  decoration: InputDecoration(
                    hintText: '选填，请先和商家协商一致',
                    hintStyle: TextStyle(color: Colors.grey),
                    border: InputBorder.none,
                  ),
                  style: TextStyle(color: Colors.grey, fontSize: 14),
                  onChanged: (value) {
                    // 记录备注
                    OrderCheckoutModel orderCheckoutModel = Provider.of(context, listen: false);
                    orderCheckoutModel.setOrderMemo(store.storeId, value);
                  },
                ),
              ),
            ],
          ),
          SizedBox(height: 12),
          Row(
            children: <Widget>[
              Expanded(
                child: Container(),
              ),
              Text.rich(
                TextSpan(
                  text: '共$subtotalQuantity件 ',
                  style: TextStyle(color: Colors.grey, fontSize: 13),
                  children: [
                    TextSpan(text: '小计：'),
                    TextSpan(
                      text: '￥',
                      style: TextStyle(color: Theme.of(context).accentColor, fontSize: 10),
                    ),
                    TextSpan(
                      text: '$subtotalRmb',
                      style: TextStyle(color: Theme.of(context).accentColor, fontSize: 14),
                    ),
                    if (subtotalJfb > 0)
                      TextSpan(
                        text: '分',
                        style: TextStyle(color: Theme.of(context).accentColor, fontSize: 10),
                      ),
                    if (subtotalJfb > 0)
                      TextSpan(
                        text: '$subtotalJfb',
                        style: TextStyle(color: Theme.of(context).accentColor, fontSize: 14),
                      ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _BottomWidget extends StatelessWidget {
  final OrderConfirm orderConfirm;

  const _BottomWidget({
    Key key,
    @required this.orderConfirm,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 运费、数量
    double totalFreight = 0;
    int totalQuantity = 0;
    for (Store store in orderConfirm.carts) {
      totalFreight += store.freight;
      for (Cart cart in store.cartList) {
        totalQuantity += cart.quantity;
      }
    }
    // 合计
    String totalRmb;
    String totalJfb;
    for (Price price in orderConfirm.totalPriceVos) {
      switch (price.coinType) {
        case 'RMB':
          totalRmb = price.pointCoinString;
          break;
        case 'JFB':
          totalJfb = price.pointCoinString;
          break;
      }
    }
    return Container(
      decoration: BoxDecoration(
        color: Color(0xFF313740),
      ),
      height: 54,
      child: Row(
        children: <Widget>[
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 30),
              child: Text('共$totalQuantity件'),
            ),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Text.rich(
                TextSpan(
                  text: '合计：',
                  children: [
                    TextSpan(
                      text: '￥',
                      style: TextStyle(fontSize: 11),
                    ),
                    TextSpan(
                      text: totalRmb,
                      style: TextStyle(fontSize: 18),
                    ),
                    if (totalJfb != null)
                      TextSpan(
                        text: '分',
                        style: TextStyle(fontSize: 10),
                      ),
                    if (totalJfb != null)
                      TextSpan(
                        text: totalJfb,
                        style: TextStyle(fontSize: 18),
                      ),
                  ],
                ),
              ),
              Text(
                totalFreight == 0 ? '免运费' : '运费 ￥$totalFreight',
                style: TextStyle(fontSize: 11),
              ),
            ],
          ),
          Container(
            width: 96,
            margin: EdgeInsets.symmetric(horizontal: 8),
            child: RaisedButton(
              onPressed: () => _orderCheckout(context),
              child: Text('提交订单'),
            ),
          ),
        ],
      ),
    );
  }

  void _orderCheckout(BuildContext context) async {
    OrderConfirmModel orderConfirmModel = Provider.of(context, listen: false);
    OrderCheckoutModel orderCheckoutModel = Provider.of(context, listen: false);

    showModalBottomSheet(
      context: context,
      builder: (context) {
        return MultiProvider(
          providers: [
            ChangeNotifierProvider.value(value: orderConfirmModel),
            ChangeNotifierProvider.value(value: orderCheckoutModel)
          ],
          child: _BottomSheetWidget(),
        );
      },
    );
  }
}

class _BottomSheetWidget extends StatefulWidget {
  @override
  __BottomSheetWidgetState createState() => __BottomSheetWidgetState();
}

class __BottomSheetWidgetState extends State<_BottomSheetWidget> {
  int _selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    // 显示合计金额
    OrderConfirmModel model = Provider.of(context, listen: false);
    // 合计
    String totalRmb;
    for (Price price in model.orderConfirm.totalPriceVos) {
      switch (price.coinType) {
        case 'RMB':
          totalRmb = price.pointCoinString;
          break;
      }
    }
    return Theme(
      data: lightTheme(),
      child: Material(
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Container(
                alignment: Alignment.center,
                height: 45,
                child: Text(
                  '确认付款',
                  style: TextStyle(fontSize: 19),
                ),
              ),
              Divider(height: 1),
              Container(
                margin: EdgeInsets.only(top: 30),
                child: Text.rich(
                  TextSpan(
                    text: '￥',
                    style: TextStyle(fontSize: 23),
                    children: [
                      TextSpan(
                        text: '$totalRmb',
                        style: TextStyle(fontSize: 46),
                      ),
                    ],
                  ),
                ),
              ),
              ListTile(
                title: Text(
                  '微信支付',
                  style: TextStyle(color: Colors.grey),
                ),
                trailing: Image.asset(
                  _selectedIndex == 0
                      ? 'assets/images/cart/check_checked.png'
                      : 'assets/images/cart/check_normal.png',
                  width: 17,
                ),
                onTap: () {
                  setState(() {
                    _selectedIndex = 0;
                  });
                },
              ),
              Divider(height: 1, indent: 12, endIndent: 12),
              ListTile(
                title: Text(
                  '支付宝支付',
                  style: TextStyle(color: Colors.grey),
                ),
                trailing: Image.asset(
                  _selectedIndex == 1
                      ? 'assets/images/cart/check_checked.png'
                      : 'assets/images/cart/check_normal.png',
                  width: 17,
                ),
                onTap: () {
                  setState(() {
                    _selectedIndex = 1;
                  });
                },
              ),
              Divider(height: 1, indent: 12, endIndent: 12),
              Container(
                width: 375 - 24.0,
                margin: EdgeInsets.all(12),
                child: Consumer<OrderCheckoutModel>(
                  builder: (context, model, child) {
                    switch (model.viewState) {
                      case ViewState.busy:
                        return RaisedButton(
                          onPressed: null,
                          child: SizedBox(
                            width: 14,
                            height: 14,
                            child: CircularProgressIndicator(),
                          ),
                        );
                      default:
                        return RaisedButton(
                          onPressed: () => _onPayClicked(context),
                          child: Text('立即付款'),
                        );
                    }
                  },
                  child: RaisedButton(
                    onPressed: () => _onPayClicked(context),
                    child: Text('立即付款'),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _onPayClicked(BuildContext context) async {
    OrderConfirmModel orderConfirmModel = Provider.of(context, listen: false);
    OrderCheckoutModel orderCheckoutModel = Provider.of(context, listen: false);
    // 地址
    int addressId =
        orderCheckoutModel.address?.id ?? orderConfirmModel.orderConfirm.defaultAddress?.id;
    // 支付
    String payType = '_PAY';
    switch (_selectedIndex) {
      case 0:
        payType = 'WX_PAY';
        break;
      case 1:
        payType = 'ALI_PAY';
        break;
    }
    // 商品
    Map<String, int> storeCarts = orderConfirmModel.cartIdQuantity;
    // 获取签名并发起支付
    ViewState viewState = await orderCheckoutModel.orderCheckout(addressId, payType, storeCarts);
    switch (viewState) {
      case ViewState.error:
        showToast(orderCheckoutModel.errorMessage);
        break;
      default:
        showToast('支付成功');
        // 返回首页，并跳转到订单待发货tab页面。
        Navigator.of(context).pushNamedAndRemoveUntil(
          '/order',
          ModalRoute.withName('/main'),
          arguments: OrderPageArgs(null, 1),
        );
        break;
    }
  }
}
